package com.itlong.cloud.network.tcp.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.Charset;

/**
 * <desc>
 *      初始化netty连接通道服务。
 * </desc>
 *
 * @createDate 2018/11/6
 */
public class ParkingServer {
	
	public void run(int port) {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
        		.channel(NioServerSocketChannel.class)
        		.childHandler(new ChannelInitializer<SocketChannel>() { 
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
						ByteBuf filed = Unpooled.copiedBuffer("\001", Charset.forName("UTF-8"));
						ch.pipeline().addLast(new DelimiterBasedFrameDecoder(81920*10,filed));

                    	//字符串传输数据
						ch.pipeline().addLast("decoder", new StringDecoder(Charset.forName("UTF-8")));
						ch.pipeline().addLast("encoder", new StringEncoder(Charset.forName("UTF-8")));
    					ch.pipeline().addLast("handler",new ServerStringHandler());
                    }
                })
        		.option(ChannelOption.SO_BACKLOG, 10240)
				.option(ChannelOption.SO_RCVBUF, 10*1024*1024)
				.option(ChannelOption.SO_SNDBUF, 1024*1024)
				.childOption(ChannelOption.RCVBUF_ALLOCATOR, AdaptiveRecvByteBufAllocator.DEFAULT)
				//.childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(20480))
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        
        try {
			ChannelFuture f = bootstrap.bind(port).sync();
			 f.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
	}
	
}
